package com.lee.rabbitmq;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2023-12-25
 * Time: 17:26
 */

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消费消息
 */
public class Comsumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 2.设置参数
        factory.setHost("47.236.41.211");
        factory.setPort(5672);
        factory.setVirtualHost("forum");
        factory.setUsername("ITforum");
        factory.setPassword("ihatehacker555");
        // 3.获取连接
        // 4.获取channel
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        // 5.创建队列
        channel.queueDeclare("hello.Queue", true, false, false, null);
        // 6.监听指定队列
        // String queue,
        // boolean autoAck,
        // String consumerTag,
        // Consumer callback

//        Consumer consumer = new DefaultConsumer()
        channel.basicConsume("hello.Queue", true, "consumer-hello", new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                // consumerTag 消费者身份标识
                // envelop 信息集合：交换机、路由key。。。
                // properties 配置信息
                // body 真实数据
                System.out.println("consumerTag = "+consumerTag);
                System.out.println("exchange = "+envelope.getExchange());
                System.out.println("routingKey = "+envelope.getRoutingKey());
                System.out.println("properties = "+properties);
                System.out.println("body = "+new String(body));
            }
        });

    }
}
